var co = require('co');
var OSS = require('ali-oss');

var fs = require("fs");
//path模块，可以生产相对和绝对路径
var path = require("path");

var client = new OSS({
  region: 'oss-cn-shanghai',
  accessKeyId: 'gh4Uwme1bYC2KmzO',
  accessKeySecret: '7nvGxCf9jVYzUfC3TaRP2iVeIb29w5',
  bucket: 'dqye-admin'
});
function uploadFile(){
  readFile(path.join(path.resolve(),"dist"),"",function(key,localfile){
    co(function* () {
    var result = yield client.put(key, localfile);
    console.log(result.name+":"+result.res.status);
    //console.log(result);
    }).catch(function (err) {
      console.log(err);
    })
  });
};
//获取后缀名
function getdir(url){
  var arr = url.split('.');
  var len = arr.length;
  return arr[len-1];
}
//获取文件数组
function readFile(realpath,name,callback){
  var name = name;
  fs.readdir(realpath,function(err,files){
      if (err) throw err;
      files.forEach(function(filename){
          fs.stat(path.join(realpath,filename),function(err, stats){
              if (err) throw err;
              //是文件
              if(stats.isFile()){
                //console.log(path.join(name,filename));
                var dir = getdir(filename);
                callback(path.join(name,filename),path.join(realpath,filename));
              }else if(stats.isDirectory()){
                  var dirName = filename;
                  readFile(path.join(realpath,filename),path.join(name,dirName),callback);
                  //利用arguments.callee(path.join())这种形式利用自身函数，会报错
                  //arguments.callee(path.join(readurl,filename),name+'/'+dirName);
              }
          });
      });
  });
}
uploadFile();
